import axios from "axios";

const BASE_URL = process.env.REACT_APP_API_URL;

const request = axios.create({
  baseURL: BASE_URL,
  timeout: 10000,
});

// 将对象转换为FormData的辅助函数
const convertToFormData = (data) => {
  const formData = new FormData();

  if (data && typeof data === "object") {
    Object.keys(data).forEach((key) => {
      // 处理嵌套对象和数组
      if (typeof data[key] === "object" && !(data[key] instanceof File)) {
        formData.append(key, JSON.stringify(data[key]));
      } else {
        formData.append(key, data[key]);
      }
    });
  }

  return formData;
};

request.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("wechat_token");
    if (token) {
      config.headers["Authorization"] = `Bearer ${token}`;
    }

    // 如果是POST请求且不是FormData且content-Type不是json，自动转换为FormData
    if (
      config.method?.toLowerCase() === "post" &&
      config.headers["Content-Type"] !== "application/json" &&
      !(config.data instanceof FormData) &&
      config.data !== null &&
      config.data !== undefined
    ) {
      config.data = convertToFormData(config.data);
      config.headers["Content-Type"] = "multipart/form-data";
    } else if (config.data instanceof FormData) {
      config.headers["Content-Type"] = "multipart/form-data";
    } else if (
      config.headers["Content-Type"] === undefined ||
      config.headers["Content-Type"] === null
    ) {
      config.headers["Content-Type"] = "application/json";
    }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

request.interceptors.response.use(
  (response) => {
    if (response.status === 200) {
      if (response.data.code === 401) {
        // navigator()
      }
      return response.data;
    } else {
      const errMsg = new Error(response.data);
      errMsg.code = response.status;
      return Promise.reject(errMsg);
    }
  },
  (error) => {
    return Promise.reject(error);
  }
);

export default request;
